home *** CD-ROM | disk | FTP | other *** search
/ TeX 1995 July / TeX CD-ROM July 1995 (Disc 1)(Walnut Creek)(1995).ISO / macros / latex209 / contrib / latexinfo / C / latexindex.c < prev    next >
C/C++ Source or Header  |  1991-11-13  |  39KB  |  1,680 lines

  1. /* Prepare TeX index dribble output into an actual index.
  2.  
  3.    Version 1.40
  4.    25 October 1991
  5.  
  6.    Copyright (C) 1987, 1991 Free Software Foundation, Inc.
  7.  
  8.    This program is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 2, or (at your option)
  11.    any later version.
  12.  
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
  21.  
  22. #include <stdio.h>
  23. #include <ctype.h>
  24. #include "getopt.h"
  25.  
  26. #ifdef STDC_HEADERS
  27. #include <string.h>
  28. #include <stdlib.h>
  29. #define bzero(p, n) memset((p), '\0', (n))
  30. #else
  31. char *getenv ();
  32. char *malloc ();
  33. char *realloc ();
  34. #endif
  35.  
  36. #ifdef POSIX
  37. #include <unistd.h>
  38. #else
  39. long lseek ();
  40. #endif
  41.  
  42. char *mktemp ();
  43.  
  44. #ifdef VMS
  45. #include <file.h>
  46.  
  47. #define EXIT_SUCCESS ((1 << 28) | 1)
  48. #define EXIT_FATAL ((1 << 28) | 4)
  49. #define unlink delete
  50. #else /* !VMS */
  51. #include <sys/file.h>
  52.  
  53. #define EXIT_SUCCESS 0
  54. #define EXIT_FATAL 1
  55. #endif /* VMS */
  56.  
  57. #ifndef SEEK_SET
  58. #define SEEK_SET 0
  59. #define SEEK_CUR 1
  60. #define SEEK_END 2
  61. #endif
  62.  
  63. /* When sorting in core, this structure describes one line
  64.    and the position and length of its first keyfield.  */
  65.  
  66. struct lineinfo
  67. {
  68.   char *text;            /* The actual text of the line. */
  69.   union
  70.   {
  71.     /* The start of the key (for textual comparison), */
  72.     char *text;
  73.     /* or the numeric value (for numeric comparison). */
  74.     long number;
  75.   } key;
  76.   long keylen;            /* Length of key field. */
  77. };
  78.  
  79. /* This structure describes a field to use as a sort key. */
  80.  
  81. struct keyfield
  82. {
  83.   /* Number of words to skip.  */
  84.   int startwords;
  85.  
  86.   /* Number of additional chars to skip, to start of field. */
  87.   int startchars;
  88.  
  89.   /* Similar, from beg (or end) of line, to find end of field. */
  90.   int endwords;
  91.  
  92.   int endchars;
  93.  
  94.   /* If nonzero, ignore spaces and tabs within the field. */
  95.   char ignore_blanks;
  96.  
  97.   /* If nonzero, convert upper case to lower before comparing. */
  98.   char fold_case;
  99.  
  100.   /* If nonzero, compare in reverse order. */
  101.   char reverse;
  102.  
  103.   /* If nonzero, parse text as an integer and compare the integers. */
  104.   char numeric;
  105.  
  106.   /* If nonzero, sort according to position within the file. */
  107.   char positional;
  108.  
  109.   /* If nonzero, count balanced-braced groupings as fields. */
  110.   char braced;
  111. };
  112.  
  113. /* Vector of keyfields to use. */
  114. struct keyfield keyfields[3];
  115.  
  116. /* Number of keyfields stored in that vector.  */
  117. int num_keyfields = 3;
  118.  
  119. /* Vector of input file names, terminated with a null pointer. */
  120. char **infiles;
  121.  
  122. /* Vector of corresponding output file names, or NULL, meaning default it
  123.    (add an `s' to the end). */
  124. char **outfiles;
  125.  
  126. /* Length of `infiles'. */
  127. int num_infiles;
  128.  
  129. /* Pointer to the array of pointers to lines being sorted. */
  130. char **linearray;
  131.  
  132. /* The allocated length of `linearray'. */
  133. long lines;
  134.  
  135. /* Directory to use for temporary files.  On Unix, it ends with a slash.  */
  136. char *tempdir;
  137.  
  138. /* Start of filename to use for temporary files.  */
  139. char *tempbase;
  140.  
  141. /* Number of last temporary file.  */
  142. int tempcount;
  143.  
  144. /* Number of last temporary file already deleted.
  145.    Temporary files are deleted by `flush_tempfiles' in order of creation.  */
  146. int last_deleted_tempcount;
  147.  
  148. /* During in-core sort, this points to the base of the data block
  149.    which contains all the lines of data.  */
  150. char *text_base;
  151.  
  152. /* Additional command switches .*/
  153.  
  154. /* Nonzero means do not delete tempfiles -- for debugging. */
  155. int keep_tempfiles;
  156.  
  157. /* Forward declarations of functions in this file. */
  158.  
  159. void decode_command ();
  160. void sort_in_core ();
  161. void sort_offline ();
  162. char **parsefile ();
  163. char *find_field ();
  164. char *find_pos ();
  165. long find_value ();
  166. char *find_braced_pos ();
  167. char *find_braced_end ();
  168. void writelines ();
  169. int compare_field ();
  170. int compare_full ();
  171. long readline ();
  172. int merge_files ();
  173. int merge_direct ();
  174. void pfatal_with_name ();
  175. void fatal ();
  176. void error ();
  177. char *xmalloc ();
  178. char *xrealloc ();
  179. char *concat ();
  180. char *maketempname ();
  181. void flush_tempfiles ();
  182. char *tempcopy ();
  183.  
  184. #define MAX_IN_CORE_SORT 500000
  185.  
  186. void
  187. main (argc, argv)
  188.      int argc;
  189.      char **argv;
  190. {
  191.   int i;
  192.  
  193.   tempcount = 0;
  194.   last_deleted_tempcount = 0;
  195.  
  196.   /* Describe the kind of sorting to do. */
  197.   /* The first keyfield uses the first braced field and folds case. */
  198.   keyfields[0].braced = 1;
  199.   keyfields[0].fold_case = 1;
  200.   keyfields[0].endwords = -1;
  201.   keyfields[0].endchars = -1;
  202.  
  203.   /* The second keyfield uses the second braced field, numerically. */
  204.   keyfields[1].braced = 1;
  205.   keyfields[1].numeric = 1;
  206.   keyfields[1].startwords = 1;
  207.   keyfields[1].endwords = -1;
  208.   keyfields[1].endchars = -1;
  209.  
  210.   /* The third keyfield (which is ignored while discarding duplicates)
  211.      compares the whole line. */
  212.   keyfields[2].endwords = -1;
  213.   keyfields[2].endchars = -1;
  214.  
  215.   decode_command (argc, argv);
  216.  
  217.   tempbase = mktemp (concat ("txiXXXXXX", "", ""));
  218.  
  219.   /* Process input files completely, one by one.  */
  220.  
  221.   for (i = 0; i < num_infiles; i++)
  222.     {
  223.       int desc;
  224.       long ptr;
  225.       char *outfile;
  226.  
  227.       desc = open (infiles[i], O_RDONLY, 0);
  228.       if (desc < 0)
  229.     pfatal_with_name (infiles[i]);
  230.       lseek (desc, 0L, SEEK_END);
  231.       ptr = lseek (desc, 0L, SEEK_CUR);
  232.  
  233.       close (desc);
  234.  
  235.       outfile = outfiles[i];
  236.       if (!outfile)
  237.     {
  238.       outfile = concat (infiles[i], "s", "");
  239.     }
  240.  
  241.       if (ptr < MAX_IN_CORE_SORT)
  242.     /* Sort a small amount of data. */
  243.     sort_in_core (infiles[i], ptr, outfile);
  244.       else
  245.     sort_offline (infiles[i], ptr, outfile);
  246.     }
  247.  
  248.   flush_tempfiles (tempcount);
  249.   exit (EXIT_SUCCESS);
  250. }
  251.  
  252. /* Decode the command line arguments to set the parameter variables
  253.    and set up the vector of keyfields and the vector of input files. */
  254.  
  255. void
  256. decode_command (argc, argv)
  257.      int argc;
  258.      char **argv;
  259. {
  260.   int optc;
  261.   char **ip;
  262.   char **op;
  263.  
  264.   /* Store default values into parameter variables. */
  265.  
  266.   tempdir = getenv ("TMPDIR");
  267. #ifdef VMS
  268.   if (tempdir == NULL)
  269.     tempdir = "sys$scratch:";
  270. #else
  271.   if (tempdir == NULL)
  272.     tempdir = "/tmp/";
  273.   else
  274.     tempdir = concat (tempdir, "/", "");
  275. #endif
  276.  
  277.   keep_tempfiles = 0;
  278.  
  279.   /* Allocate ARGC input files, which must be enough.  */
  280.  
  281.   infiles = (char **) xmalloc (argc * sizeof (char *));
  282.   outfiles = (char **) xmalloc (argc * sizeof (char *));
  283.   ip = infiles;
  284.   op = outfiles;
  285.  
  286.   while ((optc = getopt (argc, argv, "-ko:")) != EOF)
  287.     {
  288.       switch (optc)
  289.     {
  290.     case 1:        /* Non-option filename. */
  291.       *ip++ = optarg;
  292.       *op++ = NULL;
  293.       break;
  294.  
  295.     case 'k':
  296.       keep_tempfiles = 1;
  297.       break;
  298.  
  299.     case 'o':
  300.       if (op > outfiles)
  301.         *(op - 1) = optarg;
  302.       break;
  303.  
  304.     default:
  305.       fprintf (stderr, "\
  306. Usage: %s [-k] infile [-o outfile] ...\n", argv[0]);
  307.       exit (1);
  308.     }
  309.     }
  310.  
  311.   /* Record number of keyfields and terminate list of filenames. */
  312.   num_infiles = ip - infiles;
  313.   *ip = 0;
  314. }
  315.  
  316. /* Return a name for a temporary file. */
  317.  
  318. char *
  319. maketempname (count)
  320.      int count;
  321. {
  322.   char tempsuffix[10];
  323.   sprintf (tempsuffix, "%d", count);
  324.   return concat (tempdir, tempbase, tempsuffix);
  325. }
  326.  
  327. /* Delete all temporary files up to TO_COUNT. */
  328.  
  329. void
  330. flush_tempfiles (to_count)
  331.      int to_count;
  332. {
  333.   if (keep_tempfiles)
  334.     return;
  335.   while (last_deleted_tempcount < to_count)
  336.     unlink (maketempname (++last_deleted_tempcount));
  337. }
  338.  
  339. /* Copy the input file open on IDESC into a temporary file
  340.    and return the temporary file name. */
  341.  
  342. #define BUFSIZE 1024
  343.  
  344. char *
  345. tempcopy (idesc)
  346.      int idesc;
  347. {
  348.   char *outfile = maketempname (++tempcount);
  349.   int odesc;
  350.   char buffer[BUFSIZE];
  351.  
  352.   odesc = open (outfile, O_WRONLY | O_CREAT, 0666);
  353.  
  354.   if (odesc < 0)
  355.     pfatal_with_name (outfile);
  356.  
  357.   while (1)
  358.     {
  359.       int nread = read (idesc, buffer, BUFSIZE);
  360.       write (odesc, buffer, nread);
  361.       if (!nread)
  362.     break;
  363.     }
  364.  
  365.   close (odesc);
  366.  
  367.   return outfile;
  368. }
  369.  
  370. /* Compare LINE1 and LINE2 according to the specified set of keyfields. */
  371.  
  372. int
  373. compare_full (line1, line2)
  374.      char **line1, **line2;
  375. {
  376.   int i;
  377.  
  378.   /* Compare using the first keyfield;
  379.      if that does not distinguish the lines, try the second keyfield;
  380.      and so on. */
  381.  
  382.   for (i = 0; i < num_keyfields; i++)
  383.     {
  384.       long length1, length2;
  385.       char *start1 = find_field (&keyfields[i], *line1, &length1);
  386.       char *start2 = find_field (&keyfields[i], *line2, &length2);
  387.       int tem = compare_field (&keyfields[i], start1, length1, *line1 - text_base,
  388.                    start2, length2, *line2 - text_base);
  389.       if (tem)
  390.     {
  391.       if (keyfields[i].reverse)
  392.         return -tem;
  393.       return tem;
  394.     }
  395.     }
  396.  
  397.   return 0;            /* Lines match exactly. */
  398. }
  399.  
  400. /* Compare LINE1 and LINE2, described by structures
  401.    in which the first keyfield is identified in advance.
  402.    For positional sorting, assumes that the order of the lines in core
  403.    reflects their nominal order.  */
  404.  
  405. int
  406. compare_prepared (line1, line2)
  407.      struct lineinfo *line1, *line2;
  408. {
  409.   int i;
  410.   int tem;
  411.   char *text1, *text2;
  412.  
  413.   /* Compare using the first keyfield, which has been found for us already. */
  414.   if (keyfields->positional)
  415.     {
  416.       if (line1->text - text_base > line2->text - text_base)
  417.     tem = 1;
  418.       else
  419.     tem = -1;
  420.     }
  421.   else if (keyfields->numeric)
  422.     tem = line1->key.number - line2->key.number;
  423.   else
  424.     tem = compare_field (keyfields, line1->key.text, line1->keylen, 0,
  425.              line2->key.text, line2->keylen, 0);
  426.   if (tem)
  427.     {
  428.       if (keyfields->reverse)
  429.     return -tem;
  430.       return tem;
  431.     }
  432.  
  433.   text1 = line1->text;
  434.   text2 = line2->text;
  435.  
  436.   /* Compare using the second keyfield;
  437.      if that does not distinguish the lines, try the third keyfield;
  438.      and so on. */
  439.  
  440.   for (i = 1; i < num_keyfields; i++)
  441.     {
  442.       long length1, length2;
  443.       char *start1 = find_field (&keyfields[i], text1, &length1);
  444.       char *start2 = find_field (&keyfields[i], text2, &length2);
  445.       int tem = compare_field (&keyfields[i], start1, length1, text1 - text_base,
  446.                    start2, length2, text2 - text_base);
  447.       if (tem)
  448.     {
  449.       if (keyfields[i].reverse)
  450.         return -tem;
  451.       return tem;
  452.     }
  453.     }
  454.  
  455.   return 0;            /* Lines match exactly. */
  456. }
  457.  
  458. /* Like compare_full but more general.
  459.    You can pass any strings, and you can say how many keyfields to use.
  460.    POS1 and POS2 should indicate the nominal positional ordering of
  461.    the two lines in the input.  */
  462.  
  463. int
  464. compare_general (str1, str2, pos1, pos2, use_keyfields)
  465.      char *str1, *str2;
  466.      long pos1, pos2;
  467.      int use_keyfields;
  468. {
  469.   int i;
  470.  
  471.   /* Compare using the first keyfield;
  472.      if that does not distinguish the lines, try the second keyfield;
  473.      and so on. */
  474.  
  475.   for (i = 0; i < use_keyfields; i++)
  476.     {
  477.       long length1, length2;
  478.       char *start1 = find_field (&keyfields[i], str1, &length1);
  479.       char *start2 = find_field (&keyfields[i], str2, &length2);
  480.       int tem = compare_field (&keyfields[i], start1, length1, pos1,
  481.                    start2, length2, pos2);
  482.       if (tem)
  483.     {
  484.       if (keyfields[i].reverse)
  485.         return -tem;
  486.       return tem;
  487.     }
  488.     }
  489.  
  490.   return 0;            /* Lines match exactly. */
  491. }
  492.  
  493. /* Find the start and length of a field in STR according to KEYFIELD.
  494.    A pointer to the starting character is returned, and the length
  495.    is stored into the int that LENGTHPTR points to.  */
  496.  
  497. char *
  498. find_field (keyfield, str, lengthptr)
  499.      struct keyfield *keyfield;
  500.      char *str;
  501.      long *lengthptr;
  502. {
  503.   char *start;
  504.   char *end;
  505.   char *(*fun) ();
  506.  
  507.   if (keyfield->braced)
  508.     fun = find_braced_pos;
  509.   else
  510.     fun = find_pos;
  511.  
  512.   start = (*fun) (str, keyfield->startwords, keyfield->startchars,
  513.           keyfield->ignore_blanks);
  514.   if (keyfield->endwords < 0)
  515.     {
  516.       if (keyfield->braced)
  517.     end = find_braced_end (start);
  518.       else
  519.     {
  520.       end = start;
  521.       while (*end && *end != '\n')
  522.         end++;
  523.     }
  524.     }
  525.   else
  526.     {
  527.       end = (*fun) (str, keyfield->endwords, keyfield->endchars, 0);
  528.       if (end - str < start - str)
  529.     end = start;
  530.     }
  531.   *lengthptr = end - start;
  532.   return start;
  533. }
  534.  
  535. /* Return a pointer to a specified place within STR,
  536.    skipping (from the beginning) WORDS words and then CHARS chars.
  537.    If IGNORE_BLANKS is nonzero, we skip all blanks
  538.    after finding the specified word.  */
  539.  
  540. char *
  541. find_pos (str, words, chars, ignore_blanks)
  542.      char *str;
  543.      int words, chars;
  544.      int ignore_blanks;
  545. {
  546.   int i;
  547.   char *p = str;
  548.  
  549.   for (i = 0; i < words; i++)
  550.     {
  551.       char c;
  552.       /* Find next bunch of nonblanks and skip them. */
  553.       while ((c = *p) == ' ' || c == '\t')
  554.     p++;
  555.       while ((c = *p) && c != '\n' && !(c == ' ' || c == '\t'))
  556.     p++;
  557.       if (!*p || *p == '\n')
  558.     return p;
  559.     }
  560.  
  561.   while (*p == ' ' || *p == '\t')
  562.     p++;
  563.  
  564.   for (i = 0; i < chars; i++)
  565.     {
  566.       if (!*p || *p == '\n')
  567.     break;
  568.       p++;
  569.     }
  570.   return p;
  571. }
  572.  
  573. /* Like find_pos but assumes that each field is surrounded by braces
  574.    and that braces within fields are balanced. */
  575.  
  576. char *
  577. find_braced_pos (str, words, chars, ignore_blanks)
  578.      char *str;
  579.      int words, chars;
  580.      int ignore_blanks;
  581. {
  582.   int i;
  583.   int bracelevel;
  584.   char *p = str;
  585.   char c;
  586.  
  587.   for (i = 0; i < words; i++)
  588.     {
  589.       bracelevel = 1;
  590.       while ((c = *p++) != '{' && c != '\n' && c)
  591.     /* Do nothing. */ ;
  592.       if (c != '{')
  593.     return p - 1;
  594.       while (bracelevel)
  595.     {
  596.       c = *p++;
  597.       if (c == '{')
  598.         bracelevel++;
  599.       if (c == '}')
  600.         bracelevel--;
  601.       if (c == '\\')
  602.         c = *p++;        /* \ quotes braces and \. */
  603.       if (c == 0 || c == '\n')
  604.         return p - 1;
  605.     }
  606.     }
  607.  
  608.   while ((c = *p++) != '{' && c != '\n' && c)
  609.     /* Do nothing. */ ;
  610.  
  611.   if (c != '{')
  612.     return p - 1;
  613.  
  614.   if (ignore_blanks)
  615.     while ((c = *p) == ' ' || c == '\t')
  616.       p++;
  617.  
  618.   for (i = 0; i < chars; i++)
  619.     {
  620.       if (!*p || *p == '\n')
  621.     break;
  622.       p++;
  623.     }
  624.   return p;
  625. }
  626.  
  627. /* Find the end of the balanced-brace field which starts at STR.
  628.    The position returned is just before the closing brace. */
  629.  
  630. char *
  631. find_braced_end (str)
  632.      char *str;
  633. {
  634.   int bracelevel;
  635.   char *p = str;
  636.   char c;
  637.  
  638.   bracelevel = 1;
  639.   while (bracelevel)
  640.     {
  641.       c = *p++;
  642.       if (c == '{')
  643.     bracelevel++;
  644.       if (c == '}')
  645.     bracelevel--;
  646.       if (c == '\\')
  647.     c = *p++;
  648.       if (c == 0 || c == '\n')
  649.     return p - 1;
  650.     }
  651.   return p - 1;
  652. }
  653.  
  654. long
  655. find_value (start, length)
  656.      char *start;
  657.      long length;
  658. {
  659.   while (length != 0L)
  660.     {
  661.       if (isdigit (*start))
  662.     return atol (start);
  663.       length--;
  664.       start++;
  665.     }
  666.   return 0l;
  667. }
  668.  
  669. /* Vector used to translate characters for comparison.
  670.    This is how we make all alphanumerics follow all else,
  671.    and ignore case in the first sorting.  */
  672. int char_order[256];
  673.  
  674. void
  675. init_char_order ()
  676. {
  677.   int i;
  678.   for (i = 1; i < 256; i++)
  679.     char_order[i] = i;
  680.  
  681.   for (i = '0'; i <= '9'; i++)
  682.     char_order[i] += 512;
  683.  
  684.   for (i = 'a'; i <= 'z'; i++)
  685.     {
  686.       char_order[i] = 512 + i;
  687.       char_order[i + 'A' - 'a'] = 512 + i;
  688.     }
  689. }
  690.  
  691. /* Compare two fields (each specified as a start pointer and a character count)
  692.    according to KEYFIELD.
  693.    The sign of the value reports the relation between the fields. */
  694.  
  695. int
  696. compare_field (keyfield, start1, length1, pos1, start2, length2, pos2)
  697.      struct keyfield *keyfield;
  698.      char *start1;
  699.      long length1;
  700.      long pos1;
  701.      char *start2;
  702.      long length2;
  703.      long pos2;
  704. {
  705.   if (keyfields->positional)
  706.     {
  707.       if (pos1 > pos2)
  708.     return 1;
  709.       else
  710.     return -1;
  711.     }
  712.   if (keyfield->numeric)
  713.     {
  714.       long value = find_value (start1, length1) - find_value (start2, length2);
  715.       if (value > 0)
  716.     return 1;
  717.       if (value < 0)
  718.     return -1;
  719.       return 0;
  720.     }
  721.   else
  722.     {
  723.       char *p1 = start1;
  724.       char *p2 = start2;
  725.       char *e1 = start1 + length1;
  726.       char *e2 = start2 + length2;
  727.  
  728.       while (1)
  729.     {
  730.       int c1, c2;
  731.  
  732.       if (p1 == e1)
  733.         c1 = 0;
  734.       else
  735.         c1 = *p1++;
  736.       if (p2 == e2)
  737.         c2 = 0;
  738.       else
  739.         c2 = *p2++;
  740.  
  741.       if (char_order[c1] != char_order[c2])
  742.         return char_order[c1] - char_order[c2];
  743.       if (!c1)
  744.         break;
  745.     }
  746.  
  747.       /* Strings are equal except possibly for case.  */
  748.       p1 = start1;
  749.       p2 = start2;
  750.       while (1)
  751.     {
  752.       int c1, c2;
  753.  
  754.       if (p1 == e1)
  755.         c1 = 0;
  756.       else
  757.         c1 = *p1++;
  758.       if (p2 == e2)
  759.         c2 = 0;
  760.       else
  761.         c2 = *p2++;
  762.  
  763.       if (c1 != c2)
  764.         /* Reverse sign here so upper case comes out last.  */
  765.         return c2 - c1;
  766.       if (!c1)
  767.         break;
  768.     }
  769.  
  770.       return 0;
  771.     }
  772. }
  773.  
  774. /* A `struct linebuffer' is a structure which holds a line of text.
  775.    `readline' reads a line from a stream into a linebuffer
  776.    and works regardless of the length of the line.  */
  777.  
  778. struct linebuffer
  779. {
  780.   long size;
  781.   char *buffer;
  782. };
  783.  
  784. /* Initialize LINEBUFFER for use. */
  785.  
  786. void
  787. initbuffer (linebuffer)
  788.      struct linebuffer *linebuffer;
  789. {
  790.   linebuffer->size = 200;
  791.   linebuffer->buffer = (char *) xmalloc (200);
  792. }
  793.  
  794. /* Read a line of text from STREAM into LINEBUFFER.
  795.    Return the length of the line.  */
  796.  
  797. long
  798. readline (linebuffer, stream)
  799.      struct linebuffer *linebuffer;
  800.      FILE *stream;
  801. {
  802.   char *buffer = linebuffer->buffer;
  803.   char *p = linebuffer->buffer;
  804.   char *end = p + linebuffer->size;
  805.  
  806.   while (1)
  807.     {
  808.       int c = getc (stream);
  809.       if (p == end)
  810.     {
  811.       buffer = (char *) xrealloc (buffer, linebuffer->size *= 2);
  812.       p += buffer - linebuffer->buffer;
  813.       end += buffer - linebuffer->buffer;
  814.       linebuffer->buffer = buffer;
  815.     }
  816.       if (c < 0 || c == '\n')
  817.     {
  818.       *p = 0;
  819.       break;
  820.     }
  821.       *p++ = c;
  822.     }
  823.  
  824.   return p - buffer;
  825. }
  826.  
  827. /* Sort an input file too big to sort in core.  */
  828.  
  829. void
  830. sort_offline (infile, nfiles, total, outfile)
  831.      char *infile;
  832.      int nfiles;
  833.      long total;
  834.      char *outfile;
  835. {
  836.   /* More than enough. */
  837.   int ntemps = 2 * (total + MAX_IN_CORE_SORT - 1) / MAX_IN_CORE_SORT;
  838.   char **tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
  839.   FILE *istream = fopen (infile, "r");
  840.   int i;
  841.   struct linebuffer lb;
  842.   long linelength;
  843.   int failure = 0;
  844.  
  845.   initbuffer (&lb);
  846.  
  847.   /* Read in one line of input data.  */
  848.  
  849.   linelength = readline (&lb, istream);
  850.  
  851.   if (lb.buffer[0] != '\\')
  852.     {
  853.       error ("%s: not a texinfo index file", infile);
  854.       return;
  855.     }
  856.  
  857.   /* Split up the input into `ntemps' temporary files, or maybe fewer,
  858.      and put the new files' names into `tempfiles' */
  859.  
  860.   for (i = 0; i < ntemps; i++)
  861.     {
  862.       char *outname = maketempname (++tempcount);
  863.       FILE *ostream = fopen (outname, "w");
  864.       long tempsize = 0;
  865.  
  866.       if (!ostream)
  867.     pfatal_with_name (outname);
  868.       tempfiles[i] = outname;
  869.  
  870.       /* Copy lines into this temp file as long as it does not make file
  871.      "too big" or until there are no more lines.  */
  872.  
  873.       while (tempsize + linelength + 1 <= MAX_IN_CORE_SORT)
  874.     {
  875.       tempsize += linelength + 1;
  876.       fputs (lb.buffer, ostream);
  877.       putc ('\n', ostream);
  878.  
  879.       /* Read another line of input data.  */
  880.  
  881.       linelength = readline (&lb, istream);
  882.       if (!linelength && feof (istream))
  883.         break;
  884.  
  885.       if (lb.buffer[0] != '\\')
  886.         {
  887.           error ("%s: not a texinfo index file", infile);
  888.           failure = 1;
  889.           goto fail;
  890.         }
  891.     }
  892.       fclose (ostream);
  893.       if (feof (istream))
  894.     break;
  895.     }
  896.  
  897.   free (lb.buffer);
  898.  
  899. fail:
  900.   /* Record number of temp files we actually needed.  */
  901.  
  902.   ntemps = i;
  903.  
  904.   /* Sort each tempfile into another tempfile.
  905.     Delete the first set of tempfiles and put the names of the second
  906.     into `tempfiles'. */
  907.  
  908.   for (i = 0; i < ntemps; i++)
  909.     {
  910.       char *newtemp = maketempname (++tempcount);
  911.       sort_in_core (&tempfiles[i], MAX_IN_CORE_SORT, newtemp);
  912.       if (!keep_tempfiles)
  913.     unlink (tempfiles[i]);
  914.       tempfiles[i] = newtemp;
  915.     }
  916.  
  917.   if (failure)
  918.     return;
  919.  
  920.   /* Merge the tempfiles together and indexify. */
  921.  
  922.   merge_files (tempfiles, ntemps, outfile);
  923. }
  924.  
  925. /* Sort INFILE, whose size is TOTAL,
  926.    assuming that is small enough to be done in-core,
  927.    then indexify it and send the output to OUTFILE (or to stdout).  */
  928.  
  929. void
  930. sort_in_core (infile, total, outfile)
  931.      char *infile;
  932.      long total;
  933.      char *outfile;
  934. {
  935.   char **nextline;
  936.   char *data = (char *) xmalloc (total + 1);
  937.   char *file_data;
  938.   long file_size;
  939.   int i;
  940.   FILE *ostream = stdout;
  941.   struct lineinfo *lineinfo;
  942.  
  943.   /* Read the contents of the file into the moby array `data'. */
  944.  
  945.   int desc = open (infile, O_RDONLY, 0);
  946.  
  947.   if (desc < 0)
  948.     fatal ("failure reopening %s", infile);
  949.   for (file_size = 0;;)
  950.     {
  951.       i = read (desc, data + file_size, total - file_size);
  952.       if (i <= 0)
  953.     break;
  954.       file_size += i;
  955.     }
  956.   file_data = data;
  957.   data[file_size] = 0;
  958.  
  959.   close (desc);
  960.  
  961.   if (file_size > 0 && data[0] != '\\')
  962.     {
  963.       error ("%s: not a texinfo index file", infile);
  964.       return;
  965.     }
  966.  
  967.   init_char_order ();
  968.  
  969.   /* Sort routines want to know this address. */
  970.  
  971.   text_base = data;
  972.  
  973.   /* Create the array of pointers to lines, with a default size
  974.      frequently enough.  */
  975.  
  976.   lines = total / 50;
  977.   if (!lines)
  978.     lines = 2;
  979.   linearray = (char **) xmalloc (lines * sizeof (char *));
  980.  
  981.   /* `nextline' points to the next free slot in this array.
  982.      `lines' is the allocated size.  */
  983.  
  984.   nextline = linearray;
  985.  
  986.   /* Parse the input file's data, and make entries for the lines.  */
  987.  
  988.   nextline = parsefile (infile, nextline, file_data, file_size);
  989.   if (nextline == 0)
  990.     {
  991.       error ("%s: not a texinfo index file", infile);
  992.       return;
  993.     }
  994.  
  995.   /* Sort the lines. */
  996.  
  997.   /* If we have enough space, find the first keyfield of each line in advance.
  998.      Make a `struct lineinfo' for each line, which records the keyfield
  999.      as well as the line, and sort them.  */
  1000.  
  1001.   lineinfo = (struct lineinfo *) malloc ((nextline - linearray) * sizeof (struct lineinfo));
  1002.  
  1003.   if (lineinfo)
  1004.     {
  1005.       struct lineinfo *lp;
  1006.       char **p;
  1007.  
  1008.       for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
  1009.     {
  1010.       lp->text = *p;
  1011.       lp->key.text = find_field (keyfields, *p, &lp->keylen);
  1012.       if (keyfields->numeric)
  1013.         lp->key.number = find_value (lp->key.text, lp->keylen);
  1014.     }
  1015.  
  1016.       qsort (lineinfo, nextline - linearray, sizeof (struct lineinfo), compare_prepared);
  1017.  
  1018.       for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
  1019.     *p = lp->text;
  1020.  
  1021.       free (lineinfo);
  1022.     }
  1023.   else
  1024.     qsort (linearray, nextline - linearray, sizeof (char *), compare_full);
  1025.  
  1026.   /* Open the output file. */
  1027.  
  1028.   if (outfile)
  1029.     {
  1030.       ostream = fopen (outfile, "w");
  1031.       if (!ostream)
  1032.     pfatal_with_name (outfile);
  1033.     }
  1034.  
  1035.   writelines (linearray, nextline - linearray, ostream);
  1036.   if (outfile)
  1037.     fclose (ostream);
  1038.  
  1039.   free (linearray);
  1040.   free (data);
  1041. }
  1042.  
  1043. /* Parse an input string in core into lines.
  1044.    DATA is the input string, and SIZE is its length.
  1045.    Data goes in LINEARRAY starting at NEXTLINE.
  1046.    The value returned is the first entry in LINEARRAY still unused.
  1047.    Value 0 means input file contents are invalid.  */
  1048.  
  1049. char **
  1050. parsefile (filename, nextline, data, size)
  1051.      char *filename;
  1052.      char **nextline;
  1053.      char *data;
  1054.      long size;
  1055. {
  1056.   char *p, *end;
  1057.   char **line = nextline;
  1058.  
  1059.   p = data;
  1060.   end = p + size;
  1061.   *end = 0;
  1062.  
  1063.   while (p != end)
  1064.     {
  1065.       if (p[0] != '\\')
  1066.     return 0;
  1067.  
  1068.       *line = p;
  1069.       while (*p && *p != '\n')
  1070.     p++;
  1071.       if (p != end)
  1072.     p++;
  1073.  
  1074.       line++;
  1075.       if (line == linearray + lines)
  1076.     {
  1077.       char **old = linearray;
  1078.       linearray = (char **) xrealloc (linearray, sizeof (char *) * (lines *= 4));
  1079.       line += linearray - old;
  1080.     }
  1081.     }
  1082.  
  1083.   return line;
  1084. }
  1085.  
  1086. /* Indexification is a filter applied to the sorted lines
  1087.    as they are being written to the output file.
  1088.    Multiple entries for the same name, with different page numbers,
  1089.    get combined into a single entry with multiple page numbers.
  1090.    The first braced field, which is used for sorting, is discarded.
  1091.    However, its first character is examined, folded to lower case,
  1092.    and if it is different from that in the previous line fed to us
  1093.    a \initial line is written with one argument, the new initial.
  1094.  
  1095.    If an entry has four braced fields, then the second and third
  1096.    constitute primary and secondary names.
  1097.    In this case, each change of primary name
  1098.    generates a \primary line which contains only the primary name,
  1099.    and in between these are \secondary lines which contain
  1100.    just a secondary name and page numbers. */
  1101.  
  1102. /* The last primary name we wrote a \primary entry for.
  1103.    If only one level of indexing is being done, this is the last name seen. */
  1104. char *lastprimary;
  1105. /* Length of storage allocated for lastprimary. */
  1106. int lastprimarylength;
  1107.  
  1108. /* Similar, for the secondary name. */
  1109. char *lastsecondary;
  1110. int lastsecondarylength;
  1111.  
  1112. /* Zero if we are not in the middle of writing an entry.
  1113.    One if we have written the beginning of an entry but have not
  1114.    yet written any page numbers into it.
  1115.    Greater than one if we have written the beginning of an entry
  1116.    plus at least one page number. */
  1117. int pending;
  1118.  
  1119. /* The initial (for sorting purposes) of the last primary entry written.
  1120.    When this changes, a \initial {c} line is written */
  1121.  
  1122. char *lastinitial;
  1123.  
  1124. int lastinitiallength;
  1125.  
  1126. /* When we need a string of length 1 for the value of lastinitial,
  1127.    store it here.  */
  1128.  
  1129. char lastinitial1[2];
  1130.  
  1131. /* Initialize static storage for writing an index. */
  1132.  
  1133. void
  1134. init_index ()
  1135. {
  1136.   pending = 0;
  1137.   lastinitial = lastinitial1;
  1138.   lastinitial1[0] = 0;
  1139.   lastinitial1[1] = 0;
  1140.   lastinitiallength = 0;
  1141.   lastprimarylength = 100;
  1142.   lastprimary = (char *) xmalloc (lastprimarylength + 1);
  1143.   bzero (lastprimary, lastprimarylength + 1);
  1144.   lastsecondarylength = 100;
  1145.   lastsecondary = (char *) xmalloc (lastsecondarylength + 1);
  1146.   bzero (lastsecondary, lastsecondarylength + 1);
  1147. }
  1148.  
  1149. /* Indexify.  Merge entries for the same name,
  1150.    insert headers for each initial character, etc.  */
  1151.  
  1152. void
  1153. indexify (line, ostream)
  1154.      char *line;
  1155.      FILE *ostream;
  1156. {
  1157.   char *primary, *secondary, *pagenumber;
  1158.   int primarylength, secondarylength = 0, pagelength;
  1159.   int nosecondary;
  1160.   int initiallength;
  1161.   char *initial;
  1162.   char initial1[2];
  1163.   register char *p;
  1164.  
  1165.   /* First, analyze the parts of the entry fed to us this time. */
  1166.  
  1167.   p = find_braced_pos (line, 0, 0, 0);
  1168.   if (*p == '{')
  1169.     {
  1170.       initial = p;
  1171.       /* Get length of inner pair of braces starting at `p',
  1172.      including that inner pair of braces.  */
  1173.       initiallength = find_braced_end (p + 1) + 1 - p;
  1174.     }
  1175.   else
  1176.     {
  1177.       initial = initial1;
  1178.       initial1[0] = *p;
  1179.       initial1[1] = 0;
  1180.       initiallength = 1;
  1181.  
  1182.       if (initial1[0] >= 'a' && initial1[0] <= 'z')
  1183.     initial1[0] -= 040;
  1184.     }
  1185.  
  1186.   pagenumber = find_braced_pos (line, 1, 0, 0);
  1187.   pagelength = find_braced_end (pagenumber) - pagenumber;
  1188.   if (pagelength == 0)
  1189.     abort ();
  1190.  
  1191.   primary = find_braced_pos (line, 2, 0, 0);
  1192.   primarylength = find_braced_end (primary) - primary;
  1193.  
  1194.   secondary = find_braced_pos (line, 3, 0, 0);
  1195.   nosecondary = !*secondary;
  1196.   if (!nosecondary)
  1197.     secondarylength = find_braced_end (secondary) - secondary;
  1198.  
  1199.   /* If the primary is different from before, make a new primary entry. */
  1200.   if (strncmp (primary, lastprimary, primarylength))
  1201.     {
  1202.       /* Close off current secondary entry first, if one is open. */
  1203.       if (pending)
  1204.     {
  1205.       fputs ("}\n", ostream);
  1206.       pending = 0;
  1207.     }
  1208.  
  1209.       /* If this primary has a different initial, include an entry for
  1210.      the initial. */
  1211.       if (initiallength != lastinitiallength ||
  1212.       strncmp (initial, lastinitial, initiallength))
  1213.     {
  1214.       if ( strncmp (initial, "\\", 1) == 0)
  1215.         { fprintf (ostream, "\\initial {\\back}\n"); }
  1216.         else
  1217.         {
  1218.           fprintf (ostream, "\\initial {");
  1219.           fwrite (initial, 1, initiallength, ostream);
  1220.           fprintf (ostream, "}\n", initial);
  1221.         }
  1222.  
  1223.       if (initial == initial1)
  1224.         {
  1225.           lastinitial = lastinitial1;
  1226.           *lastinitial1 = *initial1;
  1227.         }
  1228.       else
  1229.         {
  1230.           lastinitial = initial;
  1231.         }
  1232.       lastinitiallength = initiallength;
  1233.     }
  1234.  
  1235.       /* Make the entry for the primary.  */
  1236.       if (nosecondary)
  1237.     fputs ("\\entry {", ostream);
  1238.       else
  1239.     fputs ("\\primary {", ostream);
  1240.       fwrite (primary, primarylength, 1, ostream);
  1241.       if (nosecondary)
  1242.     {
  1243.       fputs ("}{", ostream);
  1244.       pending = 1;
  1245.     }
  1246.       else
  1247.     fputs ("}\n", ostream);
  1248.  
  1249.       /* Record name of most recent primary. */
  1250.       if (lastprimarylength < primarylength)
  1251.     {
  1252.       lastprimarylength = primarylength + 100;
  1253.       lastprimary = (char *) xrealloc (lastprimary,
  1254.                        1 + lastprimarylength);
  1255.     }
  1256.       strncpy (lastprimary, primary, primarylength);
  1257.       lastprimary[primarylength] = 0;
  1258.  
  1259.       /* There is no current secondary within this primary, now. */
  1260.       lastsecondary[0] = 0;
  1261.     }
  1262.  
  1263.   /* Should not have an entry with no subtopic following one with a subtopic. */
  1264.  
  1265.   if (nosecondary && *lastsecondary)
  1266.     error ("entry %s follows an entry with a secondary name", line);
  1267.  
  1268.   /* Start a new secondary entry if necessary. */
  1269.   if (!nosecondary && strncmp (secondary, lastsecondary, secondarylength))
  1270.     {
  1271.       if (pending)
  1272.     {
  1273.       fputs ("}\n", ostream);
  1274.       pending = 0;
  1275.     }
  1276.  
  1277.       /* Write the entry for the secondary.  */
  1278.       fputs ("\\secondary {", ostream);
  1279.       fwrite (secondary, secondarylength, 1, ostream);
  1280.       fputs ("}{", ostream);
  1281.       pending = 1;
  1282.  
  1283.       /* Record name of most recent secondary. */
  1284.       if (lastsecondarylength < secondarylength)
  1285.     {
  1286.       lastsecondarylength = secondarylength + 100;
  1287.       lastsecondary = (char *) xrealloc (lastsecondary,
  1288.                          1 + lastsecondarylength);
  1289.     }
  1290.       strncpy (lastsecondary, secondary, secondarylength);
  1291.       lastsecondary[secondarylength] = 0;
  1292.     }
  1293.  
  1294.   /* Here to add one more page number to the current entry. */
  1295.   if (pending++ != 1)
  1296.     fputs (", ", ostream);    /* Punctuate first, if this is not the first. */
  1297.   fwrite (pagenumber, pagelength, 1, ostream);
  1298. }
  1299.  
  1300. /* Close out any unfinished output entry. */
  1301.  
  1302. void
  1303. finish_index (ostream)
  1304.      FILE *ostream;
  1305. {
  1306.   if (pending)
  1307.     fputs ("}\n", ostream);
  1308.   free (lastprimary);
  1309.   free (lastsecondary);
  1310. }
  1311.  
  1312. /* Copy the lines in the sorted order.
  1313.    Each line is copied out of the input file it was found in. */
  1314.  
  1315. void
  1316. writelines (linearray, nlines, ostream)
  1317.      char **linearray;
  1318.      int nlines;
  1319.      FILE *ostream;
  1320. {
  1321.   char **stop_line = linearray + nlines;
  1322.   char **next_line;
  1323.  
  1324.   init_index ();
  1325.  
  1326.   /* Output the text of the lines, and free the buffer space. */
  1327.  
  1328.   for (next_line = linearray; next_line != stop_line; next_line++)
  1329.     {
  1330.       /* If -u was specified, output the line only if distinct from previous one.  */
  1331.       if (next_line == linearray
  1332.       /* Compare previous line with this one, using only the
  1333.          explicitly specd keyfields. */
  1334.       || compare_general (*(next_line - 1), *next_line, 0L, 0L, num_keyfields - 1))
  1335.     {
  1336.       char *p = *next_line;
  1337.       char c;
  1338.  
  1339.       while ((c = *p++) && c != '\n')
  1340.         /* Do nothing. */ ;
  1341.       *(p - 1) = 0;
  1342.       indexify (*next_line, ostream);
  1343.     }
  1344.     }
  1345.  
  1346.   finish_index (ostream);
  1347. }
  1348.  
  1349. /* Assume (and optionally verify) that each input file is sorted;
  1350.    merge them and output the result.
  1351.    Returns nonzero if any input file fails to be sorted.
  1352.  
  1353.    This is the high-level interface that can handle an unlimited
  1354.    number of files.  */
  1355.  
  1356. #define MAX_DIRECT_MERGE 10
  1357.  
  1358. int
  1359. merge_files (infiles, nfiles, outfile)
  1360.      char **infiles;
  1361.      int nfiles;
  1362.      char *outfile;
  1363. {
  1364.   char **tempfiles;
  1365.   int ntemps;
  1366.   int i;
  1367.   int value = 0;
  1368.   int start_tempcount = tempcount;
  1369.  
  1370.   if (nfiles <= MAX_DIRECT_MERGE)
  1371.     return merge_direct (infiles, nfiles, outfile);
  1372.  
  1373.   /* Merge groups of MAX_DIRECT_MERGE input files at a time,
  1374.      making a temporary file to hold each group's result.  */
  1375.  
  1376.   ntemps = (nfiles + MAX_DIRECT_MERGE - 1) / MAX_DIRECT_MERGE;
  1377.   tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
  1378.   for (i = 0; i < ntemps; i++)
  1379.     {
  1380.       int nf = MAX_DIRECT_MERGE;
  1381.       if (i + 1 == ntemps)
  1382.     nf = nfiles - i * MAX_DIRECT_MERGE;
  1383.       tempfiles[i] = maketempname (++tempcount);
  1384.       value |= merge_direct (&infiles[i * MAX_DIRECT_MERGE], nf, tempfiles[i]);
  1385.     }
  1386.  
  1387.   /* All temporary files that existed before are no longer needed
  1388.      since their contents have been merged into our new tempfiles.
  1389.      So delete them.  */
  1390.   flush_tempfiles (start_tempcount);
  1391.  
  1392.   /* Now merge the temporary files we created.  */
  1393.  
  1394.   merge_files (tempfiles, ntemps, outfile);
  1395.  
  1396.   free (tempfiles);
  1397.  
  1398.   return value;
  1399. }
  1400.  
  1401. /* Assume (and optionally verify) that each input file is sorted;
  1402.    merge them and output the result.
  1403.    Returns nonzero if any input file fails to be sorted.
  1404.  
  1405.    This version of merging will not work if the number of
  1406.    input files gets too high.  Higher level functions
  1407.    use it only with a bounded number of input files.  */
  1408.  
  1409. int
  1410. merge_direct (infiles, nfiles, outfile)
  1411.      char **infiles;
  1412.      int nfiles;
  1413.      char *outfile;
  1414. {
  1415.   struct linebuffer *lb1, *lb2;
  1416.   struct linebuffer **thisline, **prevline;
  1417.   FILE **streams;
  1418.   int i;
  1419.   int nleft;
  1420.   int lossage = 0;
  1421.   int *file_lossage;
  1422.   struct linebuffer *prev_out = 0;
  1423.   FILE *ostream = stdout;
  1424.  
  1425.   if (outfile)
  1426.     {
  1427.       ostream = fopen (outfile, "w");
  1428.     }
  1429.   if (!ostream)
  1430.     pfatal_with_name (outfile);
  1431.  
  1432.   init_index ();
  1433.  
  1434.   if (nfiles == 0)
  1435.     {
  1436.       if (outfile)
  1437.     fclose (ostream);
  1438.       return 0;
  1439.     }
  1440.  
  1441.   /* For each file, make two line buffers.
  1442.      Also, for each file, there is an element of `thisline'
  1443.      which points at any time to one of the file's two buffers,
  1444.      and an element of `prevline' which points to the other buffer.
  1445.      `thisline' is supposed to point to the next available line from the file,
  1446.      while `prevline' holds the last file line used,
  1447.      which is remembered so that we can verify that the file is properly sorted. */
  1448.  
  1449.   /* lb1 and lb2 contain one buffer each per file. */
  1450.   lb1 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
  1451.   lb2 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
  1452.  
  1453.   /* thisline[i] points to the linebuffer holding the next available line in file i,
  1454.      or is zero if there are no lines left in that file.  */
  1455.   thisline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *));
  1456.   /* prevline[i] points to the linebuffer holding the last used line from file i.
  1457.      This is just for verifying that file i is properly sorted.  */
  1458.   prevline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *));
  1459.   /* streams[i] holds the input stream for file i.  */
  1460.   streams = (FILE **) xmalloc (nfiles * sizeof (FILE *));
  1461.   /* file_lossage[i] is nonzero if we already know file i is not properly sorted.  */
  1462.   file_lossage = (int *) xmalloc (nfiles * sizeof (int));
  1463.  
  1464.   /* Allocate and initialize all that storage. */
  1465.  
  1466.   for (i = 0; i < nfiles; i++)
  1467.     {
  1468.       initbuffer (&lb1[i]);
  1469.       initbuffer (&lb2[i]);
  1470.       thisline[i] = &lb1[i];
  1471.       prevline[i] = &lb2[i];
  1472.       file_lossage[i] = 0;
  1473.       streams[i] = fopen (infiles[i], "r");
  1474.       if (!streams[i])
  1475.     pfatal_with_name (infiles[i]);
  1476.  
  1477.       readline (thisline[i], streams[i]);
  1478.     }
  1479.  
  1480.   /* Keep count of number of files not at eof. */
  1481.   nleft = nfiles;
  1482.  
  1483.   while (nleft)
  1484.     {
  1485.       struct linebuffer *best = 0;
  1486.       struct linebuffer *exch;
  1487.       int bestfile = -1;
  1488.       int i;
  1489.  
  1490.       /* Look at the next avail line of each file; choose the least one.  */
  1491.  
  1492.       for (i = 0; i < nfiles; i++)
  1493.     {
  1494.       if (thisline[i] &&
  1495.           (!best ||
  1496.            0 < compare_general (best->buffer, thisline[i]->buffer,
  1497.                  (long) bestfile, (long) i, num_keyfields)))
  1498.         {
  1499.           best = thisline[i];
  1500.           bestfile = i;
  1501.         }
  1502.     }
  1503.  
  1504.       /* Output that line, unless it matches the previous one and we
  1505.      don't want duplicates. */
  1506.  
  1507.       if (!(prev_out &&
  1508.         !compare_general (prev_out->buffer, best->buffer, 0L, 1L, num_keyfields - 1)))
  1509.     indexify (best->buffer, ostream);
  1510.       prev_out = best;
  1511.  
  1512.       /* Now make the line the previous of its file, and fetch a new
  1513.      line from that file.  */
  1514.  
  1515.       exch = prevline[bestfile];
  1516.       prevline[bestfile] = thisline[bestfile];
  1517.       thisline[bestfile] = exch;
  1518.  
  1519.       while (1)
  1520.     {
  1521.       /* If the file has no more, mark it empty. */
  1522.  
  1523.       if (feof (streams[bestfile]))
  1524.         {
  1525.           thisline[bestfile] = 0;
  1526.           nleft--;        /* Update the number of files still not empty. */
  1527.           break;
  1528.         }
  1529.       readline (thisline[bestfile], streams[bestfile]);
  1530.       if (thisline[bestfile]->buffer[0] || !feof (streams[bestfile]))
  1531.         break;
  1532.     }
  1533.     }
  1534.  
  1535.   finish_index (ostream);
  1536.  
  1537.   /* Free all storage and close all input streams. */
  1538.  
  1539.   for (i = 0; i < nfiles; i++)
  1540.     {
  1541.       fclose (streams[i]);
  1542.       free (lb1[i].buffer);
  1543.       free (lb2[i].buffer);
  1544.     }
  1545.   free (file_lossage);
  1546.   free (lb1);
  1547.   free (lb2);
  1548.   free (thisline);
  1549.   free (prevline);
  1550.   free (streams);
  1551.  
  1552.   if (outfile)
  1553.     fclose (ostream);
  1554.  
  1555.   return lossage;
  1556. }
  1557.  
  1558. /* Print error message and exit.  */
  1559.  
  1560. void
  1561. fatal (s1, s2)
  1562.      char *s1, *s2;
  1563. {
  1564.   error (s1, s2);
  1565.   exit (EXIT_FATAL);
  1566. }
  1567.  
  1568. /* Print error message.  S1 is printf control string, S2 is arg for it. */
  1569.  
  1570. void
  1571. error (s1, s2)
  1572.      char *s1, *s2;
  1573. {
  1574.   printf ("texindex: ");
  1575.   printf (s1, s2);
  1576.   printf ("\n");
  1577. }
  1578.  
  1579. void
  1580. perror_with_name (name)
  1581.      char *name;
  1582. {
  1583. #ifdef VMS
  1584. #include <errno.h>
  1585.   extern noshare int sys_nerr;
  1586.   extern noshare char *sys_errlist[];
  1587. #else
  1588.   extern int errno, sys_nerr;
  1589.   extern char *sys_errlist[];
  1590. #endif
  1591.   char *s;
  1592.  
  1593.   if (errno < sys_nerr)
  1594.     s = concat ("", sys_errlist[errno], " for %s");
  1595.   else
  1596.     s = "cannot open %s";
  1597.   error (s, name);
  1598. }
  1599.  
  1600. void
  1601. pfatal_with_name (name)
  1602.      char *name;
  1603. {
  1604.   extern int errno, sys_nerr;
  1605.   extern char *sys_errlist[];
  1606.   char *s;
  1607.  
  1608.   if (errno < sys_nerr)
  1609.     s = concat ("", sys_errlist[errno], " for %s");
  1610.   else
  1611.     s = "cannot open %s";
  1612.   fatal (s, name);
  1613. }
  1614.  
  1615. /* Return a newly-allocated string whose contents concatenate those of
  1616.    S1, S2, S3.  */
  1617.  
  1618. char *
  1619. concat (s1, s2, s3)
  1620.      char *s1, *s2, *s3;
  1621. {
  1622.   int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  1623.   char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  1624.  
  1625.   strcpy (result, s1);
  1626.   strcpy (result + len1, s2);
  1627.   strcpy (result + len1 + len2, s3);
  1628.   *(result + len1 + len2 + len3) = 0;
  1629.  
  1630.   return result;
  1631. }
  1632.  
  1633. /* Like malloc but get fatal error if memory is exhausted.  */
  1634.  
  1635. char *
  1636. xmalloc (size)
  1637.      unsigned size;
  1638. {
  1639.   char *result = malloc (size);
  1640.   if (!result)
  1641.     fatal ("virtual memory exhausted", 0);
  1642.   return result;
  1643. }
  1644.  
  1645.  
  1646. char *
  1647. xrealloc (ptr, size)
  1648.      char *ptr;
  1649.      unsigned size;
  1650. {
  1651.   char *result = realloc (ptr, size);
  1652.   if (!result)
  1653.     fatal ("virtual memory exhausted");
  1654.   return result;
  1655. }
  1656.  
  1657. #if defined(USG) || defined(VMS)
  1658. void
  1659. bzero (b, length)
  1660.      register char *b;
  1661.      register int length;
  1662. {
  1663. #ifdef VMS
  1664.   short zero = 0;
  1665.   long max_str = 65535;
  1666.  
  1667.   while (length > max_str)
  1668.     {
  1669.       (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
  1670.       length -= max_str;
  1671.       b += max_str;
  1672.     }
  1673.   (void) LIB$MOVC5 (&zero, &zero, &zero, &length, b);
  1674. #else
  1675.   while (length-- > 0)
  1676.     *b++ = 0;
  1677. #endif /* not VMS */
  1678. }
  1679. #endif /* defined(USG) || defined(VMS) */
  1680.